Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

264
Visualizações
keep getting this errror :" Cast to ObjectId failed for value" using mongodb with nodejs

I am new to coding and trying to build an APi using NOde js, express and mongodb

here is my code

router.get('/:id', async(req, res) => {  
console.log(req.params.id);
try{    
        const show = await Show.findById(req.params.id);
        const _iD = show._id.toHexString()
        console.log(_iD );
        if(req.params.id === _iD){
        res.json(show);      
        } else {
            res.send("not right ID");
        }
}

catch(err){
    console.log("error" + err)
}
})

it not working out,if "you enter a wrong ID intentionally " and should get " not right ID ", but it gets "Cast to Object ID failed for value".

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Try out this function

function isMongooseId(id) {
    var valid = false;
    try{
        if(id == mongoose.Types.ObjectId(""+id)) valid = true;
    } catch(e){
        valid = false;
    }
    return valid;
}

// You can use it like this,

if(isMongooseId(req.params.id)) {
    // Perform your db operation
}
about 4 years ago · Juan Pablo Isaza Relatório

0

Make sure the "intentionally wrong ID" still respect the objectId syntax (24 hexadecimal characters i would say). Otherwise you will fail at the Show.findById and jump right into the catch.

Then, i'm not sure of what your trying to do.

If you provide an ID that is not present in the collection, Show.findById will not return any object so you won't be able to get its ID with show._id.toHexString() and you will, again, jump to the catch.

And if the ID is in the collection, req.params.id === _iD will always be true and you will never reach the else.

Instead you should just check if show contain an object

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda